package com.huak.zookeeper.distributedlock.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author liuhuan
 * @date 2018/11/20 14:47
 * @description
 */
@Component
public class RedisLock {



    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean getLock(String key,String value){
        //key不存在
        if(redisTemplate.opsForValue().setIfAbsent(key,value)){

            return true;
        }
        String currentValue=redisTemplate.opsForValue().get(key);
        //如果锁过期
        if(currentValue!=null&&Long.parseLong(currentValue)<System.currentTimeMillis()){
            String oldValue=redisTemplate.opsForValue().getAndSet(key,value);
            if(oldValue!=null&&oldValue.equals(currentValue)){
                return true;
            }
        }

        return false;
    }

    public void unlock(String key,String value){
        String currentValue=redisTemplate.opsForValue().get(key);
        if(currentValue!=null&&currentValue.equals(value)){
            redisTemplate.opsForValue().getOperations().delete(key);
        }
    }
}
